#!/usr/bin/perl -l

package methods;

use strict;
use warnings;
use Data::Dumper;

my $debug = 0;

sub split_up {
	my $target = shift or die;
	my $array = shift or die;
	my $index = shift or 0;
	my $length = scalar(@$array);
	if ($length > 1) {
		my $point = &middle($array);
		if ($target == $array->[$point]) {
			return $point;
		}
		elsif ($target > $array->[$point]) {
			my $splice = splice(@$array, $point, ($length - $point));
			split_up($target, $splice, $point);
		}
		elsif ($target < $array->[$point]) {
			my $splice = splice(@$array, 0, $point);
			split_up($target, $splice, $point);
		}
	}
	elsif ($length == 1) {
		return $index;
	}
	else {
		return -1;
	}

	sub middle {
		my $a = shift;
		return int(scalar(@$a) / 2);
	}
}

sub methodical {
	my ($target, $array) = @_;
	print "got target '$target'" if $debug;
	print "got array '@$array'" if $debug;
	my $i = 0;
	foreach my $source (@$array) {
		print "i = '$i'" if $debug;
		print "source = '$source'" if $debug;
		print "\n" if $debug;
		return $i if $target == $source;
		$i++;
	}
	return -1;
}

sub for_each {
	my ($target, $array) = @_;
	for (my $i=0;$i<scalar(@$array);$i++) {
		return $i if $array->[$i] == $target;
	}
	return -1;
}


sub guess_magic_word {
	open(IN,'<','/etc/dictionaries-common/words') or die "can't open file ($!)";
	my $list = [];
	@$list = <IN>;
	close(IN);
	chomp(@$list);
	
	my $secret_index = int rand(scalar(@$list)) + 1;
	my $word = $list->[ $secret_index ];
	
	my $guessed_index;
	my $guessed_word;
	LIST: for ( my $i=1; $i < scalar(@$list); $i++ ) {
		if ($list->[$i] eq $word) {
			$guessed_index = $i;
			$guessed_word = $list->[$i];
			last LIST;
		}
	}
	
	print "I calculated the magic word $word to be at $guessed_index";
	
	if ($guessed_index == $secret_index) {
		print "that is correct";
	}
	else {
		print "wrong: index $secret_index contains $guessed_word";
	}
}

1;
